﻿/****************************** Module Header ******************************\
 * Module Name:  CNRegionComboBox.cs
 * Module Version:  1.0.0 (2012-1-9)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This componse is use for pick the chinese region.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UCF.Core.Web.CustomControls
{
    /// <summary>
    /// 中国省市区联动控件
    /// <para>使用方法:</para>
    /// <para>HTML:so:CNRegion ID="CNRegion1" runat="server" XMLUrl="/JsPlus/PlusUtilities/CNRegion/CNRegion-min.xml" </para>
    /// <para>Server:Response.Write(string.Format("Province={0};City={1};Area={2};", CNRegion1.ProvinceValue, CNRegion1.CityValue, CNRegion1.AreaValue));</para>
    /// <para>web.config:add tagPrefix="so" namespace="UCF.Core.Web.CustomControls" assembly="UCF.Core"</para>
    /// <para>Server:void page_load(){CNRegion1.ProvinceValue = "福建省";CNRegion1.CityValue = "厦门市";CNRegion1.AreaValue = "思明区";}</para>
    /// </summary>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:CNRegionComboBox runat=server></{0}:CNRegionComboBox>")]
    public class CNRegionComboBox : CompositeControl
    {
        /// <summary>
        /// 省份隐藏文本域
        /// </summary>
        private HiddenField hidProvince;
        /// <summary>
        /// 城市隐藏文本域
        /// </summary>
        private HiddenField hidCity;
        /// <summary>
        /// 地区隐藏文本域
        /// </summary>
        private HiddenField hidArea;

        /// <summary>
        /// 是否隐藏地区控件
        /// </summary>
        public bool HideArea { get; set; }

        /// <summary>
        /// 普通下拉选项框的通用编号
        /// </summary>
        public string CNRSelectGeneralID
        {
            get
            {
                String s = (String)ViewState["CNRSelectGeneralID"];
                return ((s == null) ? String.Empty : s);
            }
            set
            {
                ViewState["CNRSelectGeneralID"] = value;
            }
        }

        /// <summary>
        /// 隐藏文本域的通用编号
        /// </summary>
        public string CNRHiddenGeneralID
        {
            get
            {
                String s = (String)ViewState["CNRHiddenGeneralID"];
                return ((s == null) ? String.Empty : s);
            }
            set
            {
                ViewState["CNRHiddenGeneralID"] = value;
            }
        }

        /// <summary>
        /// 自定义省市区XML数据文件路径
        /// </summary>
        public string XMLUrl { get; set; }

        /// <summary>
        /// 是否读取value字段
        /// </summary>
        public bool IsReadValueField { get; set; }

        /// <summary>
        /// 省份的值
        /// </summary>
        public string ProvinceValue
        {
            get
            {
                EnsureChildControls();
                return this.hidProvince.Value == null ? "" : this.hidProvince.Value;
            }
            set
            {
                EnsureChildControls();
                this.hidProvince.Value = value;
            }
        }

        /// <summary>
        /// 城市的值
        /// </summary>
        public string CityValue
        {
            get
            {
                EnsureChildControls();
                return this.hidCity.Value == null ? "" : this.hidCity.Value;
            }
            set
            {
                EnsureChildControls();
                this.hidCity.Value = value;
            }
        }

        /// <summary>
        /// 地区的值
        /// </summary>
        public string AreaValue
        {
            get
            {
                EnsureChildControls();
                return this.hidArea.Value == null ? "" : this.hidArea.Value;
            }
            set
            {
                EnsureChildControls();
                this.hidArea.Value = value;
            }
        }

        /// <summary>
        /// 创建控件
        /// </summary>
        protected override void CreateChildControls()
        {
            this.hidProvince = new HiddenField();
            this.hidCity = new HiddenField();
            this.hidArea = new HiddenField();
            this.CNRHiddenGeneralID = "CNRHid" + this.ID + this.UniqueID.Replace('$', '_');
            this.CNRSelectGeneralID = "CNRSlt" + this.ID + this.UniqueID.Replace('$', '_');
            this.hidProvince.ID = this.CNRHiddenGeneralID + "p";
            this.hidCity.ID = this.CNRHiddenGeneralID + "c";
            this.hidArea.ID = this.CNRHiddenGeneralID + "a";
            this.hidProvince.ClientIDMode = ClientIDMode.Static;
            this.hidCity.ClientIDMode = ClientIDMode.Static;
            this.hidArea.ClientIDMode = ClientIDMode.Static;
            this.Controls.Add(this.hidProvince);
            this.Controls.Add(this.hidCity);
            this.Controls.Add(this.hidArea);
        }

        /// <summary>
        /// 页面预加载时间
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            this.Page.PreRenderComplete += PagePreRenderComplete;
            base.OnPreRender(e);
        }

        /// <summary>
        /// 页面预加载内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PagePreRenderComplete(object sender, EventArgs e)
        {
            String strCNRegionXML = "";
            if (this.XMLUrl != null && System.IO.File.Exists(this.Page.Server.MapPath(this.XMLUrl)))
            {
                strCNRegionXML = System.IO.File.ReadAllText(this.Page.Server.MapPath(this.XMLUrl));
            }
            else
            {
                strCNRegionXML = CNRegionData.ChineseRegionData;
            }

            String strScript = Environment.NewLine + "<script>jQuery(document).ready(function($){SetCNRegion=function(cnRegionXML,provinceID,cityID,areaID,provinceValue,cityValue,areaValue,provinceHiddenID,cityHiddenID,areaHiddenID,isReadValueField){if(!cnregion)var cnregion={};cnregion.$xmlCnRegion=$($.parseXML(cnRegionXML));cnregion.$provinceSelect=$(provinceID);cnregion.$citySelect=$(cityID);cnregion.$areaSelect=$(areaID);cnregion.provinceValue=provinceValue;cnregion.cityValue=cityValue;cnregion.areaValue=areaValue;cnregion.$provinceHidden=$(provinceHiddenID);cnregion.$cityHidden=$(cityHiddenID);cnregion.$areaHidden=$(areaHiddenID);cnregion.valueFieldName=((isReadValueField==true)?\"code\":\"name\");cnregion.InitCity=function(){cnregion.$xmlCnRegion.find(\"province[\"+cnregion.valueFieldName+\"='\"+cnregion.provinceValue+\"']\").children().each(function(){cnregion.$citySelect.append(\"<option value='\"+$(this).attr(cnregion.valueFieldName)+\"'>\"+$(this).attr(\"name\")+\"</option>\")});cnregion.$provinceHidden.val(cnregion.provinceValue)};cnregion.InitArea=function(){cnregion.$xmlCnRegion.find(\"province[\"+cnregion.valueFieldName+\"='\"+cnregion.provinceValue+\"']>city[\"+cnregion.valueFieldName+\"='\"+cnregion.cityValue+\"']\").children().each(function(){cnregion.$areaSelect.append(\"<option value='\"+$(this).attr(cnregion.valueFieldName)+\"'>\"+$(this).attr(\"name\")+\"</option>\")});cnregion.$cityHidden.val(cnregion.cityValue)};cnregion.$xmlCnRegion.find(\"province\").each(function(){cnregion.$provinceSelect.append(\"<option value='\"+$(this).attr(cnregion.valueFieldName)+\"'>\"+$(this).attr(\"name\")+\"</option>\")});if(cnregion.provinceValue){cnregion.$provinceSelect.children(\"option[value='\"+cnregion.provinceValue+\"']\").attr(\"selected\",\"selected\");cnregion.InitCity()};if(cnregion.cityValue){cnregion.$citySelect.children(\"option[value='\"+cnregion.cityValue+\"']\").attr(\"selected\",\"selected\");cnregion.InitArea()};if(cnregion.areaValue){cnregion.$areaSelect.children(\"option[value='\"+cnregion.areaValue+\"']\").attr(\"selected\",\"selected\");cnregion.$areaHidden.val(cnregion.areaValue)};cnregion.$provinceSelect.change(function(){cnregion.$citySelect.html(\"<option value=''>请选择城市</option>\");cnregion.$areaSelect.html(\"<option value=''>请选择地区</option>\");cnregion.provinceValue=cnregion.$provinceSelect.val();if(!cnregion.provinceValue)return;cnregion.InitCity()});cnregion.$citySelect.change(function(){cnregion.$areaSelect.html(\"<option value=''>请选择地区</option>\");cnregion.cityValue=cnregion.$citySelect.val();if(!cnregion.cityValue)return;cnregion.InitArea()});cnregion.$areaSelect.change(function(){cnregion.areaValue=cnregion.$areaSelect.val();cnregion.$areaHidden.val(cnregion.areaValue)})};});</script>";
            strScript += Environment.NewLine + "<script>var xmlCnregionData='" + strCNRegionXML + "';</script>";
            this.Page.ClientScript.RegisterStartupScript(typeof(CNRegionComboBox), "CNRegionComboBox", strScript);

            String strRunScript = Environment.NewLine + "<script>jQuery(document).ready(function($){SetCNRegion(xmlCnregionData,\"#" + this.CNRSelectGeneralID + "p\",\"#" + this.CNRSelectGeneralID + "c\",\"#" + this.CNRSelectGeneralID + "a\",\"" + this.hidProvince.Value + "\",\"" + this.hidCity.Value + "\",\"" + this.hidArea.Value + "\",\"#" + this.CNRHiddenGeneralID + "p\",\"#" + this.CNRHiddenGeneralID + "c\",\"#" + this.CNRHiddenGeneralID + "a\")});</script>";
            String scriptName = "CNRCB" + this.ID + this.UniqueID.Replace('$', '_');
            this.Page.ClientScript.RegisterStartupScript(typeof(CNRegionComboBox), scriptName, strRunScript);
        }

        /// <summary>
        /// 重新输出控件
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<select id=\"" + this.CNRSelectGeneralID + "p\"><option value=\"\">请选择省份</option></select>");
            writer.Write("<select id=\"" + this.CNRSelectGeneralID + "c\"><option value=\"\">请选择城市</option></select>");
            writer.Write("<select id=\"" + this.CNRSelectGeneralID + "a\""+(this.HideArea?" style=\"display:none;\"":"")+"><option value=\"\">请选择地区</option></select>");
            this.hidProvince.RenderControl(writer);
            this.hidCity.RenderControl(writer);
            this.hidArea.RenderControl(writer);
        }
    }
}
